<template>
  <div class="page-container">
    <el-breadcrumb separator="/" class="breadcrumb">
      <el-breadcrumb-item>{{ $t('Home') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('Community') }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ $t('Post') }}</el-breadcrumb-item>
    </el-breadcrumb>
    
    <div class="add-post">
      <h2 class="page-title">发布新文章</h2>
      
      <el-form @submit.prevent="submitForm" class="post-form">
        <el-form-item label="标题">
          <el-input 
            v-model="post.title" 
            required
            placeholder="请输入文章标题"
            class="title-input"
          />
        </el-form-item>
        
        <el-form-item label="封面">
          <image-upload 
            v-model="images"
            class="cover-upload" 
          />
        </el-form-item>
        
        <el-form-item label="简介">
          <el-input
            v-model="post.summary"
            type="textarea"
            :rows="3"
            placeholder="请输入文章简介"
            class="summary-input"
          />
        </el-form-item>
        
        <el-form-item label="内容">
          <WangEditor 
            v-model="post.content"
            class="content-editor" 
          />
        </el-form-item>
        
        <div class="form-actions">
          <el-button type="primary" native-type="submit">
            发布文章
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, watch } from 'vue';
import { ElMessage } from 'element-plus';
import WangEditor from '@/components/WangEditor.vue';
import { Community } from '@/model/Community';
import ApiClient from '@/api/ApiClient';
import { ApiRequest, ApiRequestBody } from '@/api/ApiRequest';
import { ApiResponse } from '@/api/ApiResponse';
import { config } from '@/config/config';
import ImageUpload from '@/components/ImageUpload.vue';

const community = reactive<Community>(JSON.parse(localStorage.getItem('community')) as Community);

interface Post {
  community_id: string;
  cover_url: string;
  title: string;
  summary: string;
  content: string;
}

const post = reactive<Post>({
  community_id: community.community_id,
  cover_url: localStorage.getItem('postDraft')?JSON.parse(localStorage.getItem('postDraft')).cover_url:"",
  title: localStorage.getItem('postDraft')?JSON.parse(localStorage.getItem('postDraft')).title:"",
  summary: localStorage.getItem('postDraft')?JSON.parse(localStorage.getItem('postDraft')).summary:"",
  content: localStorage.getItem('postDraft')?JSON.parse(localStorage.getItem('postDraft')).content:"",
});
const images = ref<{ name: string, url: string }[]>([]);

const saveDraft = () => {
  localStorage.setItem('postDraft', JSON.stringify(post));
};

onMounted(() => {
});

watch(post, () => {
  saveDraft();
}, { deep: true });

const submitForm = async () => {
  try {
    const request = new ApiRequest(
        "invoke",
        config.dao_chain_name,
        new ApiRequestBody(
            config.dao_contract_name,
            "add_post",
            {
              "community_id": post.community_id,
              "cover_url": images.value[0].url.replace(config.ipfs_gateway, 'ipfs://'),
              "title": post.title,
              "summary": post.summary,
              "content": post.content.replaceAll(config.ipfs_gateway, "ipfs://"),
            }
        )
    );
    ApiClient.sendSync(request, (response: ApiResponse) => {
        if(response.data.code_value as unknown as number === 0) {
            const contractResult = response.data.contract_result as { code: number, result: string };
            if(contractResult.code === 0){
                ElMessage.success(contractResult.result);
                localStorage.removeItem('postDraft');
                post.community_id = '';
                post.cover_url = '';
                post.title = '';
                post.summary = '';
                post.content = '';
                images.value = [];
            }else{
                ElMessage.error(contractResult.message || '操作失败');
            }
        }else{
            ElMessage.error(response.data.code);
        }
    });
  } catch (error) {
    console.error('添加文章失败:', error);
    alert('添加文章失败，请稍后再试');
  }
};
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  padding: 20px;
}

.breadcrumb {
  background: white;
  padding: 15px 20px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
  margin-bottom: 20px;
}

.add-post {
  max-width: 1000px;
  margin: 0 auto;
  background: white;
  padding: 30px;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
}

.page-title {
  font-size: 24px;
  color: #303133;
  margin-bottom: 30px;
  padding-bottom: 15px;
  border-bottom: 1px solid #ebeef5;
}

.post-form {
  margin-top: 20px;
}

.title-input :deep(.el-input__inner) {
  font-size: 16px;
  padding: 12px 15px;
}

.cover-upload {
  border: 2px dashed #dcdfe6;
  border-radius: 8px;
  padding: 20px;
  background: #fafafa;
}

.content-editor {
  margin-top: 10px;
  border: 1px solid #dcdfe6;
  border-radius: 4px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  margin-top: 30px;
  padding-top: 20px;
  border-top: 1px solid #ebeef5;
}

:deep(.el-button--primary) {
  padding: 12px 30px;
  font-size: 16px;
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.el-button--primary:hover) {
  transform: translateY(-2px);
  box-shadow: 0 4px 12px rgba(0,123,255,0.3);
}

:deep(.el-form-item__label) {
  font-size: 16px;
  font-weight: 500;
  color: #606266;
}

.summary-input :deep(.el-textarea__inner) {
  font-size: 14px;
  line-height: 1.6;
}

/* 响应式布局 */
@media (max-width: 768px) {
  .add-post {
    max-width: 100%;
    padding: 20px;
  }
  
  .page-title {
    font-size: 20px;
  }
}
</style>